/*
 * @Author: Preself
 * @Date: 2023-03-20 12:35:51
 * @LastEditors: Preself
 * @LastEditTime: 2023-03-20 12:41:38
 * @Description
 * @Content:永无Bug
 */
var length = 0;
var i = 0;
var tab = null;
var time = 15000;
var timer = null;

chrome.contextMenus.create({
  type: "normal",
  title: "识别验证码",
  checked: false,
  contexts: ["image"],
  onclick: switch_absolute_xpath, // 点击时调用方法
});

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  // 当地址栏URL变化时执行处理逻辑
  if (changeInfo.url) {
    console.log("地址栏URL变化：", changeInfo.url);
    // 在此处进行其他操作
  }
});

function desktop_notification(msg) {
  chrome.notifications.create("id", {
    type: "basic",
    title: " ", // 这里我故意使显示这个为空，显得没那么拥挤
    message: msg,
    iconUrl: "success.png",
  });
}

function switch_absolute_xpath(info, tab) {
  // console.log(info,tab)
  var src = info.srcUrl; //获取图片对象的src
  let h_x_scan_url = localStorage.getItem("h_x_scan_url");
  console.log(h_x_scan_url, "h_x_scan_url");
  if (!h_x_scan_url) {
    h_x_scan_url = "http://localhost:9911";
  }
  fetch(h_x_scan_url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      src: src,
    }),
  })
    .then((response) => response.text()) // 如果response是json的化，否则调用response.text()
    .then((i) => {
      function createElement(text) {
        var element = document.createElement("textarea");
        //设置元素只读
        element.setAttribute("readonly", "");
        element.value = text;
        document.body.appendChild(element);
        return element;
      }
      var text = i;
      // 调用桌面通知
      desktop_notification(`识别成功:${text},已复制到剪贴板`);

      // 通知定时2秒进行清理
      setTimeout(function (e) {
        // 这里的id只要和创建的时候设置id值一样就行了，就可以清理对应id的通知了
        chrome.notifications.clear("id");
      }, 4000);
      var element = createElement(text);
      element.select();
      element.setSelectionRange(0, element.value.length);
      document.execCommand("copy");
      element.remove();
    }); // 这里才能输出response.body的值
}


